// mmo_game_server/scripts/script_manager.go
package scripts

import (
    "fmt"
    "github.com/yuin/gopher-lua"
    "log"
    "sync"
)

// ScriptManager 脚本管理器
type ScriptManager struct {
    luaState *lua.LState
    mu       sync.Mutex
}

// NewScriptManager 创建新的脚本管理器
func NewScriptManager() *ScriptManager {
    l := lua.NewState()
    return &ScriptManager{
        luaState: l,
    }
}

// LoadScript 加载脚本
func (sm *ScriptManager) LoadScript(scriptPath string) error {
    sm.mu.Lock()
    defer sm.mu.Unlock()
    if err := sm.luaState.DoFile(scriptPath); err != nil {
        log.Printf("Failed to load script %s: %v", scriptPath, err)
        return err
    }
    return nil
}

// ReloadScript 重新加载脚本
func (sm *ScriptManager) ReloadScript(scriptPath string) error {
    sm.mu.Lock()
    defer sm.mu.Unlock()
    sm.luaState.Close()
    sm.luaState = lua.NewState()
    return sm.LoadScript(scriptPath)
}

// CallFunction 调用脚本函数
func (sm *ScriptManager) CallFunction(funcName string, args ...lua.LValue) ([]lua.LValue, error) {
    sm.mu.Lock()
    defer sm.mu.Unlock()
    if err := sm.luaState.CallByParam(lua.P{
        Fn:      sm.luaState.GetGlobal(funcName),
        NRet:    len(args),
        Protect: true,
    }, args...); err != nil {
        log.Printf("Failed to call Lua function %s: %v", funcName, err)
        return nil, err
    }
    results := make([]lua.LValue, len(args))
    for i := 0; i < len(args); i++ {
        results[i] = sm.luaState.Get(-len(args) + i)
    }
    sm.luaState.Pop(len(args))
    return results, nil
}